extern crate magic_crypt;

use crate::tools::db;
use magic_crypt::{new_magic_crypt, MagicCryptTrait};
use rusqlite::Connection;
use rusqlite::{params, Error};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

pub const MAGIC_TYPE_KEY: &str = "W3KmsaZLwLyOAcZoPriH8XzFFkIuxj0v";
pub const APP_DIR_NAME: &str = "devToolsFormTauri";
pub const TYPE_PASS_GEN_SETTING: &str = "pass_gen_setting";
lazy_static::lazy_static! {
    pub static ref PASS_ITEMS_CACHE: Arc<Mutex<Vec<crate::tools::pass::PassItem>>> = Default::default();
    pub static ref APP_CONFIG: Arc<Mutex<HashMap<&'static str,String>>> = Default::default();
    pub static ref PASS_GEN_SETTING: Arc<Mutex<String>> = Default::default();
    //app是否已初始化完成，第一次启动进入主界面后，此值应被修改为YES
    pub static ref APP_INIT_SUCCESS: Arc<Mutex<String>> = Arc::new(Mutex::new(String::from("NO")));
    pub static ref DB_CONNECT: Arc<Mutex<Option<Connection>>> = {
        match db::connect(){
            Ok(con) => Arc::new(Mutex::new(Some(con))),
            Err(e)=>{
                println!("{:#?}",e);
                Arc::new(Mutex::new(None))}
        }
    };
}

#[derive(serde::Serialize)]
pub struct ToolsSetting {
    pub s_id: String,
    pub s_title: String,
    pub s_type: String,
    pub s_value: String,
}

//加密方法
pub fn encrypt_str(data: &str) -> String {
    let mc = new_magic_crypt!(&MAGIC_TYPE_KEY, 256);
    let base64 = mc.encrypt_str_to_base64(data);
    base64
}
//解密方法
pub fn decrypt_str(data: &str) -> String {
    let mc = new_magic_crypt!(&MAGIC_TYPE_KEY, 256);
    match mc.decrypt_base64_to_string(data) {
        Ok(data_str) => data_str,
        Err(_) => {
            println!("解密失败!");
            "error".to_string()
        }
    }
}

pub fn get_setting_item(s_type: &str) -> Result<ToolsSetting, Error> {
    let bind = DB_CONNECT.lock().unwrap();
    let conn = bind.as_ref().unwrap();
    //let conn = crate::db::connect()?;
    conn.query_row(
        "select * from tools_setting where s_type=?1",
        params![s_type],
        |row| {
            Ok(ToolsSetting {
                s_id: row.get("s_id")?,
                s_title: row.get("s_title")?,
                s_type: row.get("s_type")?,
                s_value: row.get("s_value")?,
            })
        },
    )
}
